package com.example.litterpainterdemo.draw.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.ViewGroup
import android.widget.ImageView
import com.example.litterpainterdemo.R
import com.example.litterpainterdemo.utils.dp2px

/**
 * 该viewGroup上有图标和一个背景
 */
class ToolView(context: Context,attrs:AttributeSet?):ViewGroup(context,attrs) {
    private lateinit var mIcon:Drawable//图标
    private var iconSize:Int = 0 //图标尺寸
    private lateinit var icon:ImageView
    private lateinit var toolType: ToolType
    var toolViewListener:((ToolView, ToolType)->Unit)? = null  //回调数据
    private var mSelected = false //默认没有选中

    init {
        setBackgroundResource(R.drawable.bg_shape)
        //解析属性
        parseAttrs(attrs!!)

        //添加子控件
        addChild()

        //添加点击事件
        setOnClickListener {
            var type = toolType
            if(mSelected){ //需要取消选中
                changeToolViewState(false)
                type = ToolType.None
            }else{ //选中
                changeToolViewState(true)
            }
            toolViewListener?.let { it(this,type) }
        }
    }

    //改变状态
    fun changeToolViewState(isSelect:Boolean){

        if(isSelect){ //选中
            setBackgroundResource(R.drawable.selected_bg_shape)
        }else{ //取消选中
            setBackgroundResource(R.drawable.bg_shape)
        }
        mSelected = isSelect
    }

    //解析属性
    @SuppressLint("UseCompatLoadingForDrawables")
    private fun parseAttrs(attrs:AttributeSet?){

        val typedArray = context.obtainStyledAttributes(attrs,R.styleable.ToolView)
        mIcon = typedArray.getDrawable(R.styleable.ToolView_icon) ?: resources.getDrawable(R.drawable.logo,null)
        iconSize = typedArray.getDimension(R.styleable.ToolView_icon_size,dp2px(16)).toInt()

        val enumValue = typedArray.getInteger(R.styleable.ToolView_iconType, ToolType.None.value)
        toolType = ToolType.values()[enumValue-1]

        typedArray.recycle()
    }

    //添加子控件
    private fun addChild(){
        icon = ImageView(context).apply {
            setImageDrawable(mIcon)
        }
        //添加
        addView(icon,iconSize,iconSize)

    }


    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        val left = (width - iconSize)/2
        val top = (height - iconSize)/2
        icon.layout(left,top,left+iconSize,top+iconSize)
    }


}